package com.tmobile.books.matmadavinci;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;

import com.tmobile.books.matmadavinci.database.BookDatabase;

public class LauncherActivity extends Activity {
	private static final String TAG = "LauncherActivity";
	private SharedPreferences mPref;
	private Editor editor;
	BookDatabase bookDatabase;
	ArrayList<com.tmobile.books.matmadavinci.database.Book> listChapter;
	ProgressDialog dialog;
	// ProgressDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launcher);
		mPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		editor = mPref.edit();
		dialog = new ProgressDialog(this);
		dialog.setMessage(getString(R.string.loading));
		dialog.setCancelable(false);
		bookDatabase = BookDatabase.getInstance(getApplicationContext());
		boolean copiedDb = mPref.getBoolean(Constants.COPIED_DB, false);
		// da copy db hay chua
		if (!copiedDb) {
			// chua copy
			new CopyDBAsync().execute();
		}else {
			// da copy
			// kiem tra da luu vao bo chua
			if (!AppSingleton.getInstance().isDataLoaded()) {
				new LoadDataAsync().execute();
			} else {
				startActivity();
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	public void startReading(View v) {
		// da copy
		// kiem tra da luu vao bo chua
		if (!AppSingleton.getInstance().isDataLoaded()) {
			new LoadDataAsync().execute();
		} else {
			startActivity();
		}
	}

	private class CopyDBAsync extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();			
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Log.i(TAG, "copy start");
				Utils.copyDataBase(getApplicationContext(), getPackageName(),
						Constants.DATABASE_NAME);
				editor.putBoolean(Constants.COPIED_DB, true);
				editor.commit();	
				Log.i(TAG, "copy finished");
			} catch (IOException e) {
				Log.i(TAG, e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing())
				dialog.dismiss();
		}

	}

	private class LoadDataAsync extends AsyncTask<Void, Void, Void> {
		

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// readEpubFile(Constants.filePath);
			readBookDatabase();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing())
				dialog.dismiss();
			super.onPostExecute(result);
			AppSingleton.getInstance().setDataLoaded(true);
			startActivity();
		}

	}

	/**
	 * doc database va luu vao bo nho
	 */
	private void readBookDatabase() {
		bookDatabase = BookDatabase.getInstance(getApplicationContext());
		// xoa chuong thu 2
		bookDatabase.deleteAWord(2);
		AppSingleton.getInstance().setListBooks(bookDatabase.getAllRecords());
	}

	private void startActivity() {
		startActivity(new Intent(getApplicationContext(), MainActivity.class));
	}

	// private void readEpubFile(String filePath) {
	// AssetManager assetManager = getAssets();
	// try {
	// // find InputStream for book
	// InputStream epubInputStream = assetManager.open(filePath);
	//
	// // Load Book from inputStream
	// Book book = (new EpubReader()).readEpub(epubInputStream);
	//
	// // Log the book's authors
	// // Log.i(TAG, "author : " + book.getMetadata().getAuthors());
	//
	// // Log the book's title
	// // Log.i(TAG, "title : " + book.getTitle());
	//
	// /* Log the book's coverimage property */
	// // Bitmap coverImage =
	// // BitmapFactory.decodeStream(book.getCoverImage()
	// // .getInputStream());
	// // Log.i("epublib", "Coverimage is " + coverImage.getWidth() +
	// // " by "
	// // + coverImage.getHeight() + " pixels");
	//
	// // Log the tale of contents
	// // logTableOfContents(book.getTableOfContents().getTocReferences(),
	// // 0);
	// readTableOfContents(book);
	//
	// } catch (IOException e) {
	// Log.e(TAG, "epublib exception " + e.toString());
	// }
	//
	// String javascrips = "";
	// try {
	// // InputStream input = getResources().openRawResource(R.raw.lights);
	// InputStream input = this.getAssets().open(filePath);
	//
	// int size;
	// size = input.available();
	// byte[] buffer = new byte[size];
	// input.read(buffer);
	// input.close();
	// // byte buffer into a string
	// javascrips = new String(buffer);
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// // String html = readFile(is);
	//
	// // webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
	// // "application/epub+zip", "UTF-8", null);
	// }

	/**
	 * 
	 * Recursively Log the Table of Contents
	 * 
	 * 
	 * 
	 * @param tocReferences
	 * 
	 * @param depth
	 */

	// private void logTableOfContents(List<TOCReference> tocReferences, int
	// depth) {
	//
	// if (tocReferences == null) {
	//
	// return;
	//
	// }
	//
	// Log.i(TAG, "depth = " + depth);
	// for (TOCReference tocReference : tocReferences) {
	//
	// StringBuilder tocString = new StringBuilder();
	//
	// for (int i = 0; i < depth; i++) {
	//
	// tocString.append("\t");
	//
	// }
	//
	// tocString.append(tocReference.getTitle());
	//
	// Log.i(TAG, tocString.toString());
	// // AppSingleton.getInstance()
	// // .addToChapterContent(tocString.toString());
	// logTableOfContents(tocReference.getChildren(), depth + 1);
	//
	// }
	//
	// }

	// private void readTableOfContents(Book book) {
	// Spine spine = new Spine(book.getTableOfContents());
	// int index = 0;
	// for (SpineReference bookSection : spine.getSpineReferences()) {
	// index++;
	// // Log.d(TAG, "index " + index);{
	//
	// StringBuffer sb = new StringBuffer();
	// Resource res = bookSection.getResource();
	// try {
	// InputStream is = res.getInputStream();
	// BufferedReader r = new BufferedReader(new InputStreamReader(is));
	// String line, lineX = "";
	// while ((line = r.readLine()) != null) {
	// lineX = lineX.concat(Html.fromHtml(line).toString())
	// .concat("\n");
	// sb.append(line);
	// // Log.d(TAG, line);
	// }
	// Log.i(TAG, "index = " + index);
	// if (index != 2) {
	// // ko xu ly spine = 2 : chao mung
	// // AppSingleton.getInstance().addToChapterContent(
	// // sb.toString());
	// }
	//
	// } catch (IOException e) {
	// }
	// }
	// }

}
